<template>
  <div>
    <van-nav-bar title="用户注册" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="手机号"
        placeholder="手机号"
        :rules="[{ required: true, message: '请填写手机号' },{ pattern, message: '请输入正确的手机号' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button block type="info" native-type="submit">注册</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { addUser, getUserByUsername } from "@/api/user.js";
import Vue from "vue";
import { Form } from "vant";
import { Toast } from "vant";

Vue.use(Toast);
Vue.use(Form);
export default {
  data() {
    return {
      username: "",
      password: "",
      pattern: /^1[3456789]\d{9}$/
    };
  },
  created() {},
  computed: {},
  methods: {
    // 注册
    async onSubmit(values) {
      let rs = await getUserByUsername({ username: values.username });
      if (rs.data.length === 0) {
        let rs = await addUser(values);
        if (rs.status === 201) {
          Toast("注册成功请登录");
          this.$router.push("/login");
        } else {
          // console.log(rs);
          Toast("注册失败请重试");
        }
      } else {
        Toast("该手机号已注册 请登录");
      }

      console.log("submit", values);
    },
    // 返回上一页
    onClickLeft() {
      this.$router.go(-1);
    }
  }
};
</script>

<style lang="stylus" scoped>
.van-nav-bar >>> .van-icon {
  color: #0f0f0f !important;
}

>>> .van-button--info {
  background-color: #c3a769;
  border: none;
}
</style>
